package com.qf.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/2 14:55
 */
public class MyBatisUtil {

    private static ThreadLocal<SqlSession> sessionThreadLocal=new ThreadLocal<>();
    private static SqlSessionFactory sessionFactory;

    private static SqlSession getSession() throws Exception{
        if(sessionFactory==null) {
            InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }
        SqlSession sqlSession = sessionFactory.openSession();
        sessionThreadLocal.set(sqlSession);
        return sqlSession;
    }

    //获取mapper对象
    public static <T> T getMapper(Class<T> mapperClass){
        SqlSession sqlSession = sessionThreadLocal.get();

        if(sqlSession==null){
            try {
                sqlSession=getSession();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        T mapper = sqlSession.getMapper(mapperClass);
        return mapper;
    }

    public static void commit(){
        //需要一个sqlSession
        SqlSession sqlSession = sessionThreadLocal.get();
        if(sqlSession!=null){
            sqlSession.commit();
        }
    }

    public static void rollback(){
        SqlSession sqlSession = sessionThreadLocal.get();
        if (sqlSession!=null) {
            sqlSession.rollback();
        }
    }

    public static void close(){
        SqlSession sqlSession = sessionThreadLocal.get();
        if (sqlSession!=null) {
            sqlSession.close();
            sessionThreadLocal.remove();//移除
        }
    }



}
